import React, {Component} from 'react';
import Taro from '@tarojs/taro';
import {View, Image, Text, Radio} from '@tarojs/components'
import {AtIcon, AtSwipeAction, AtInputNumber} from 'taro-ui'
import {ShopList, LabelList} from '../../utils/server.interface'
import {platform} from '../../utils/platform-settting.service'
import {http} from '../../utils/http'
import {CAR_LIST, RESOURCE_URL, DEL_CAR, CAR_PAY, EDIT_CAR} from '../../constants/api'
import Headercar from '../components/header-car/header-car'
import {user} from '../../utils/user.service'
import LabelCar from "../components/detail-bar/label-car";
import {getHeadTop, getTempSellerId, vcmonitor} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import Float from "../../components/float/float";
import './index.scss'

type PageState = {
  loadMoreStatus: 'more' | 'noMore' | 'loading'
  list: ShopList[]
  limit: number
  edit: boolean
  frist: boolean
  goods: LabelList[]
  labelIndex: number
  labelKey: number
  isOpened: boolean
  referSellerId: number
  searchBarTop: number
  stIndex: number
}

export default class Index extends Component {

  state: PageState = {
    loadMoreStatus: 'loading',
    list: [],
    limit: 5,
    edit: false,
    frist: true,
    goods: [],
    stIndex: 0,
    isOpened: false,
    labelIndex: 0,
    labelKey: 0,
    referSellerId: 0,
    searchBarTop: 0
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const headTop: any = getHeadTop()
    const searchBarTop = headTop.statusBar > 20 ? (headTop.statusBar + headTop.top + 30) : (headTop.statusBar + headTop.top + 32)
    const referSellerId = user.bindSellerId
    const isLogin = await user.checkLogin();
    this.setState({searchBarTop, referSellerId}, async () => {
      if (isLogin) {
        const list = await this.getGoods(this.page, this.state.limit)
        this.setState({list})
      } else {
        user.jumpLogin()
      }
    })
  }

  shareParams = ''
  page = 1

  async componentDidShow() {
    vcmonitor(this)
    this.shareParams = await user.getSellerParams()
    if (!this.state.frist) {
      const list = await this.getGoods(this.page, this.state.limit)
      this.setState({list})
    }
  }

  async componentDidHide() {
    this.setState({frist: false})
  }

  onShareAppMessage() {
    return {
      title: platform.info.platformName,
      path: '/common/product/index?' + this.shareParams + `&sKey=${Taro.getStorageSync('sKey' || '')}`
    }
  }

  async onPullDownRefresh() {
    this.page = 1
    this.setState({loadMoreStatus: 'loading', list: []}, async () => {
      const list = await this.getGoods(this.page)
      this.setState({list}, () => {
        Taro.stopPullDownRefresh()
      })
    })
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      const old = this.state.list
      this.page++
      const newData = await this.getGoods(this.page)
      this.setState({list: [...old, ...newData]})
    }
  }

  async getGoods(page = 1, limit = 5) {
    const referSellerId = this.state.referSellerId
    const goodsData: any = await http.carGet<ShopList[]>(CAR_LIST, {page, limit, referSellerId})
    if (goodsData) {
      if (goodsData.length < limit) {
        this.setState({loadMoreStatus: 'noMore'})
      } else {
        this.setState({loadMoreStatus: 'more'})
      }
      return goodsData
    } else {
      this.setState({loadMoreStatus: 'noMore'})
      return []
    }
  }

  listsum(list) {
    list.map((item) => {
      let sum = 0
      let listnum = 0
      item.goods.map((val) => {
        if (val['checked']) {
          const min = Math.max(val.num, val.buy_num_min)
          const num = Math.min(min, val.buy_num_max)
          val['num'] = num
          sum += num * val.price
          listnum++
        }
      })
      item['listnum'] = listnum
      item['sum'] = sum.toFixed(2)
    })
    this.setState({list})
  }

  listEdit() {
    const {list, edit} = this.state
    if (edit) {
      list.map((item) => {
        item.goods.map((val) => {
          if (val.status > 0) {
            val['checked'] = false
          }
        })
      })
    }
    this.listsum(list)
    this.setState({list, edit: !edit})
  }

  jumpStore(id) {
    Taro.navigateTo({url: '/other/store/store?sid=' + id})
  }

  checkAll(index) {
    const {list, edit} = this.state
    list[index].goods.map((item) => {
      if (edit) {
        item['checked'] = !list[index].checked
      } else {
        if (!item.status) {
          item['checked'] = !list[index].checked
        }
      }
    })
    list[index].checked = !list[index].checked
    this.listsum(list)
    this.setState({list})
  }

  checkSelf(index, i) {
    const {list, edit} = this.state
    if (list[index].goods[i].disabled) {
      list[index].goods[i]['checked'] = false
      return
    }
    if (list[index].goods.length != 1) {
      if (edit) {
        list[index].goods[i]['checked'] = !list[index].goods[i].checked
      } else {
        if (!list[index].goods[i].status) {
          list[index].goods[i]['checked'] = !list[index].goods[i].checked
        }
      }
    } else {
      list[index].checked = !list[index].checked
      list[index].goods[i]['checked'] = !list[index].goods[i].checked
    }
    if (list[index].goods[i].is_aikucun) {
      list[index].goods.map((item: any) => {
        if (!item.is_aikucun) {
          item.disabled = true
          item['checked'] = false
        }
      })
    }
    this.reset(index)
    this.listsum(list)
    this.setState({list})
  }

  reset(index) {
    const {list} = this.state
    let isAllFalse = true
    for (let i = 0; i < list[index].goods.length; i++) {
      if (list[index].goods[i]['checked']) {
        isAllFalse = false
      }
    }
    if (isAllFalse) {
      list[index].goods.map((item: any) => {
        if (!item.is_aikucun) {
          delete item.disabled
        }
      })
    }
  }

  async handleChange(index, i, e) {
    const {list} = this.state
    const r = await http.postCar(EDIT_CAR, {
      id: list[index].goods[i].gid,
      carId: list[index].goods[i].id,
      num: e,
      productId: list[index].goods[i].topId
    })
    if (r) {
      list[index].goods[i].num = e
      this.listsum(list)
      this.setState({list})
    } else {
      Taro.showToast({
        title: '人数较多稍后再试',
        icon: 'none',
        duration: 2000
      })
    }
  }

  async carpay(index) {
    const {list, referSellerId} = this.state
    const data = []
    const sum = list[index].sum
    list[index].goods.map((item) => {
      if (item.checked) {
        data.push({id: item.id, num: item.num})
      }
    })
    if (data.length == 0) {
      Taro.showToast({
        title: '请选择结算商品',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    Taro.showLoading({
      title: '结算中',
      mask: true,
    })
    const tempSellerId = getTempSellerId(this)
    const ret = await http.postCar(CAR_PAY, {list: JSON.stringify(data), sum, referSellerId, tempSellerId})
    if (ret) {
      Taro.hideLoading()
      Taro.navigateTo({
        url: '/main/order/place?type=1&no=' + ret.orderNo
      })
    }
  }

  delcar(index, i) {
    const {list} = this.state
    Taro.showModal({
      title: '确认删除',
      content: '您确定删除该商品吗？',
      success: async result => {
        if (result.confirm) {
          Taro.showLoading({title: '删除中', mask: true})
          const id = list[index].goods[i].id;
          const r = await http.postCar(DEL_CAR, {ids: id.toString()})
          if (r) {
            list[index].goods.splice(i, 1);
            if (list[index].goods.length == 0) {
              list.splice(index, 1)
            }
            this.listsum(list)
            this.setState({list}, () => {
              Taro.hideLoading()
            })
          } else {
            Taro.showToast({
              title: '删除失败',
              icon: 'none'
            })
          }
        }
      }
    })
  }

  jumpedit(topId) {
    Taro.navigateTo({
      url: '/common/product/detail?fromShop=true&itemId=' + topId
    })
  }

  checkLabel(index, i, e) {
    e.stopPropagation()
    const {list} = this.state
    const goods = list[index].goods[i].labelList
    let stIndex = 0
    goods.map((item, key) => {
      if (list[index].goods[i].gid == item.id) {
        stIndex = key
      }
    })
    this.setState({goods, labelIndex: index, stIndex, labelKey: i, isOpened: true})
  }

  onOff(gid = 0, num?, title?, price?, stock?, img?) {
    if (gid) {
      const {list, labelIndex, labelKey} = this.state
      list[labelIndex].goods.map((item, index) => {
        if (index != labelKey) {
          if (item.gid == gid) {
            item.img = img
            item.num += num
            item.title = title
            item.price = price
            item.stock = stock
            list[labelIndex].goods.splice(labelKey, 1)
          }
        } else {
          item.img = img
          item.num = num
          item.title = title
          item.price = price
          item.stock = stock
        }
      })
      this.setState({list, isOpened: false})
    } else {
      this.setState({isOpened: false})
    }
  }

  delcarall(index) {
    const {list} = this.state
    let listnum = 0
    list[index].goods.map((item) => {
      if (item.checked) {
        listnum++
      }
    })
    if (list[index].goods.length == 0) {
      list.splice(index, 1)
    }
    if (listnum == 0) {
      Taro.showToast({
        title: '请选择您要删除的商品',
        icon: 'none'
      })
      return false;
    }
    Taro.showModal({
      title: '确认删除',
      content: '确定将你选中的' + listnum + '件商品删除吗？',
      success: async result => {
        if (result.confirm) {
          const idsary = [], goods = [];
          list[index].goods.map((item) => {
            if (item.checked) {
              idsary.push(item.id)
            } else {
              goods.push(item)
            }
          })
          const r = await http.postCar(DEL_CAR, {ids: idsary.join(',')})
          if (r) {
            list[index]['goods'] = goods
            if (list[index].goods.length == 0) {
              list.splice(index, 1)
            }
            this.listsum(list)
            this.setState({list})
          } else {
            Taro.showToast({
              title: '删除失败',
              icon: 'none'
            })
          }
        }
      }
    })
  }

  back() {
    Taro.switchTab({url: '/pages/index/index'})
  }

  render() {
    const dataColor = Taro.getStorageSync('colorData');
    const {loadMoreStatus, list, stIndex, isOpened, goods, searchBarTop, edit, labelIndex, labelKey} = this.state
    return (
      <View className='shopcar-root'>
        <GzhAuth />
        {process.env.TARO_ENV === 'weapp' && <View className='head-bg' style={`height: ${searchBarTop}Px;`}>
          <Headercar color='#333' title='购物车' />
        </View>}
        {list.length > 0 && <View className={`shop-top shop-top${process.env.TARO_ENV}`}><View
          className={edit ? "shop-top-btn bold" : "shop-top-btn"}
          onClick={this.listEdit.bind(this)}
        >{edit ? '完成' : '管理'}</View></View>}
        {list.length > 0 && <View className='shopCarBox'>
          {list.map((item, index) =>
            item.goods.length > 0 && <View className='shopCarlist' key={index}>
              <View className={list.length > 1 ? "shopCarlist-box" : "shopCarlist-box oneshop"}>
                {list.length > 1 &&
                  <View className='shopCarBox-title'><View onClick={this.checkAll.bind(this, index)}><Radio
                    checked={item.checked} color='#fe9f00' value={item.shopId}
                  /></View><View
                    className='shopCarBox-title-text'
                    onClick={this.jumpStore.bind(this, item.shopId)}
                  >{item.shopName}<AtIcon value='chevron-right' size='15'
                    color='#999'
                  /></View></View>}
                {item.goods.length > 0 && item.goods.map((val, key) =>
                  <View className='good-item-dome' key={val.id}>
                    <AtSwipeAction
                      autoClose
                      options={[
                        {
                          text: '删除',
                          style: {
                            backgroundColor: '#ca0000'
                          }
                        }
                      ]} onClick={this.delcar.bind(this, index, key)}
                    >
                      <View className='good-item' hoverClass='none'>
                        {val.status === 0 || edit
                          ? <View className='radio-box' onClick={this.checkSelf.bind(this, index, key)}><Radio
                              checked={val.checked} color='#fe9f00' value={val.gid} disabled={val.disabled}
                          /></View>
                          : <View className='radio-box'><Radio checked={val.checked} color='#fe9f00' value={val.gid}
                              disabled
                          /></View>
                        }
                        <View className={val.status === 0 || edit ? 'good-item-box' : `good-item-box disabled`}>
                          <View className='img-box' onClick={this.jumpedit.bind(this, val.topId)}>
                            {val.status > 0 && val.status != 4 &&
                              <View className='imgTop'><Image lazyLoad src={`${RESOURCE_URL}/resources/images/carout.png`}
                                mode='widthFix'
                              /></View>}
                            {val.status == 4 && <View className='imgTopright'>未开始</View>}
                            <Image lazyLoad={process.env.TARO_ENV != "h5"}
                              src={val.img + '?x-oss-process=image/resize,w_240' || 'https://resource.ivcheng.com/resources/images/zhanwei.jpg'}
                              mode='aspectFill' className='img'
                            />
                          </View>
                          <View className='title-box'>
                            <View onClick={this.jumpedit.bind(this, val.topId)}>
                              <View className='title'>{val.topTitle}</View>
                              <View className='label'
                                onClick={this.checkLabel.bind(this, index, key)}
                              ><Text>{val.title}</Text> <AtIcon
                                value='chevron-down' size='12' color='#888'
                              /></View>
                            </View>
                            <View className='price-box'>
                              <View className='price-box-left'><Text className='symbol font-family-price'
                                style={`color: ${dataColor.priceColor};margin-right: 2px;`}
                              >¥</Text><View
                                className='view-inline price font-family-price' style={`color: ${dataColor.priceColor};`}
                              ><Float value={val.price} /></View>{val.status > 0 &&
                                <Text className='num'>x{val.num}</Text>}</View>
                              {val.status === 0 && <AtInputNumber
                                className={`car-num-small ${process.env.TARO_ENV}`}
                                type='number'
                                min={val.buy_num_min}
                                max={val.buy_num_max}
                                step={1}
                                value={val.num}
                                onChange={this.handleChange.bind(this, index, key)}
                              />}
                            </View>
                          </View>
                        </View>
                      </View>
                    </AtSwipeAction>
                  </View>
                )}
              </View>
              {!isOpened && <View className={list.length <= 1 ? "goodsum bottom" : "goodsum"}>
                {list.length <= 1 &&
                  <View onClick={this.checkAll.bind(this, index)} className='bottom_check'><Radio checked={item.checked}
                    color='#fe9f00'
                    value={item.shopId}
                  /> 全选</View>}
                <View className='sumbox'>
                  <View className='left'>合计:<View className='font-family-price view-inline'>￥<Float
                    value={item.sum ? item.sum : '0'}
                  /></View></View>
                  {edit ? <View className='right' onClick={this.delcarall.bind(this, index)}>删除</View> :
                    <View onClick={this.carpay.bind(this, index)}
                      className='right'
                    >结算({item.listnum ? item.listnum : '0'})</View>}
                </View>
              </View>}
            </View>)}
        </View>}
        {list.length > 0 && list[0].goods.length > 0 &&
          <LabelCar onOff={
            this.onOff.bind(this)
          } isSeller={list[0].isSeller} isOpened={isOpened} goods={goods} stIndex={stIndex}
            stNum={list[labelIndex].goods[labelKey].num} gid={list[labelIndex].goods[labelKey].gid}
            carId={list[labelIndex].goods[labelKey].id} img={list[labelIndex].goods[labelKey].img}
            productId={list[labelIndex].goods[labelKey].topId}
          />
        }
        {(list.length == 0) && loadMoreStatus != 'loading' && <View className='listNull'>
          <Image src={`${RESOURCE_URL}/resources/images/carnull.png`} mode='widthFix' />
          <View className='text' onClick={this.back.bind(this)}>购物车空空如也，<Text>去逛逛吧~</Text></View>
        </View>}
      </View>
    )
  }
}
